# -*- coding: utf-8 -*-..,
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import tools

import datetime
from datetime import datetime
import pytz
import tzlocal
from tzlocal import get_localzone # $ pip install tzlocal
from lxml import etree
 
# ?????
#  only can be saving, afterchoosing "Active..."  => ???? 
#
# 
class crea8s_followup_partner(osv.osv):
       
    strFormatTime = '%Y-%m-%d %H:%M:%S %Z'
    strFormatTimeYMD = '%Y-%m-%d' 
    def act_helloword(self, cr, uid, ids, context={}):
       return self.write(cr, uid, ids, {'name': 'Hello word ! - PhongND said: "cr, uid, ids"'})
   
    def fields_view_get(self, cr, uid, view_id=None, view_type=None, context=None, toolbar=False, submenu=False):
          res = super(crea8s_followup_partner, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context,
                                                         toolbar=toolbar, submenu=submenu)
#           context = context or {}
#           if view_type == 'form':  #  and context.get('Followupfirst') 
#               doc = etree.XML(res['arch'], parser=None, base_url=None)
#               first_node = doc.xpath("//page[@name='crea8s_followup_tab']")
#               root = first_node[0].getparent()
#               root.insert(0, first_node[0])
#             res['arch'] = etree.tostring(doc, encoding="utf-8")
          return res
    
    def _get_amounts_and_date_crea8s(self, cr, uid, ids, name, arg, context=None):
        '''
        Function that computes values for the followup functional fields. Note that 'crea8s_payment_amount_due'
        is similar to 'credit' field on res.partner except it filters on user's company.
        '''
        res = {}
        for partner in self.browse(cr, uid, ids, context=context):
            res[partner.id] = {'crea8s_payment_amount_due': 11, 
                               'crea8s_payment_amount_overdue': 2, 
                               'crea8s_payment_earliest_due_date': datetime.now(get_localzone()).strftime(self.strFormatTimeYMD)}
        return res
    
    def _get_latest_crea8s(self, cr, uid, ids, names, arg, context=None, company_id=None):
        res={}
        if company_id == None:
            company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
        else:
            company = self.pool.get('res.company').browse(cr, uid, company_id, context=context)
        for partner in self.browse(cr, uid, ids, context=context):
#            ??? amls = partner.unreconciled_aml_ids
            latest_date = '2014-01-15' #aaa ???: datetime.strptime('2014-01-15', self.strFormatTimeYMD)
#             latest_date = False
            latest_level = 1
            latest_days = False
            latest_level_without_lit = False
           
            res[partner.id] = {'crea8s_latest_followup_date': latest_date,
                               'crea8s_latest_followup_level_id': latest_level,
                               'crea8s_latest_followup_level_id_without_lit': latest_level_without_lit}
        return res
    
    _inherit = "res.partner"
    _description = 'crea8s_followup_partner...'
    _columns = {
        
        'crea8s_name': fields.char('Name01'),
        
        'crea8s_payment_responsible_id':fields.many2one('res.users', ondelete='set null', string='Follow-up Responsible', 
                                                 help="Optionally you can assign a user to this field, which will make him responsible for the action.", 
                                                 track_visibility="onchange"), 
        'crea8s_payment_note':fields.text('Customer Payment Promise', help="Payment Note", track_visibility="onchange"),
        'crea8s_payment_next_action':fields.text('Next Action', 
                                    help="This is the next action to be taken.  It will automatically be set when the partner gets a follow-up level that requires a manual action. ", 
                                    track_visibility="onchange"), 
        'crea8s_payment_next_action_date':fields.date('Next Action Date',
                                    help="This is when the manual follow-up is needed. " \
                                    "The date will be set to the current date when the partner gets a follow-up level that requires a manual action. "\
                                    "Can be practical to set manually e.g. to see if he keeps his promises."),
        'crea8s_unreconciled_aml_ids':fields.one2many('account.move.line', 'partner_id', domain=['&', ('reconcile_id', '=', False), '&', 
                            ('account_id.active','=', True), '&', ('account_id.type', '=', 'receivable'), ('state', '!=', 'draft')]), 
        'crea8s_latest_followup_date':fields.function(_get_latest_crea8s, method=True, type='date', string="Latest Follow-up Date",
                            help="Latest date that the follow-up level of the partner was changed", 
                            store=False, multi="latest_aaa"), 
        'crea8s_latest_followup_level_id':fields.function(_get_latest_crea8s, method=True, 
            type='many2one', relation='crea8s.followup.detail', string="Latest Follow-up Level", 
            help="The maximum follow-up level", 
            store=False, 
            multi="latest_aaa"), 
        'crea8s_latest_followup_level_id_without_lit':fields.function(_get_latest_crea8s, method=True, 
            type='many2one', relation='crea8s.followup.detail', string="Latest Follow-up Level without litigation", 
            help="The maximum follow-up level without taking into account the account move lines with litigation", 
            store=False, 
            multi="latest_aaa"),
        
        'crea8s_payment_amount_due':fields.function(_get_amounts_and_date_crea8s, 
                                                 type='float', string="Amount Due",
                                                 store = True, multi="followup_01", 
                                                 ), #fnct_search=_payment_due_search 
        'crea8s_payment_amount_overdue':fields.function(_get_amounts_and_date_crea8s,
                                                 type='float', string="Amount Overdue",
                                                 store = False, multi="followup_01",  
                                                 ),# fnct_search = _payment_overdue_search
        'crea8s_payment_earliest_due_date':fields.function(_get_amounts_and_date_crea8s,
                                                type='date',
                                                string = "Worst Due Date",
                                                store = False, multi="followup_01",
                                                ), #fnct_search=_payment_earliest_date_search
# 'state': fields.selection([('draft','Draft'),
# ('confirmed','Confirmed')],'State',required=True,readonly=True)
    }
    
    def action_done_crea8s(self, cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'crea8s_payment_next_action_date': False, 'crea8s_payment_next_action':'', 'crea8s_payment_responsible_id': False}, context=context)

     
    def do_print_overdue_crea8s(self, cr, uid, ids, context=None): # == do_button_print
        print 'do_print_overdue_crea8s'
        wizard_partner_ids = []
        # ============================================
#         assert(len(ids) == 1)
# ?? browse: uid, uid
        print '+ uid: ' + str(uid)
        print '+ ids: ' + str(ids)
        company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
#         #search if the partner has accounting entries to print. If not, it may not be present in the
#         #psql view the report is based on, so we need to stop the user here.
#         if not self.pool.get('account.move.line').search(cr, uid, [
#                                                                    ('partner_id', '=', ids[0]),
#                                                                    ('account_id.type', '=', 'receivable'),
#                                                                    ('reconcile_id', '=', False),
#                                                                    ('state', '!=', 'draft'),
#                                                                    ('company_id', '=', company_id),
#                                                                   ], context=context):
#             raise osv.except_osv(_('Error!'),_("The partner does not have any accounting entries to print in the overdue report for the current company."))
        self.message_post(cr, uid, [ids[0]], body=_('Printed overdue payments report - phongnd'), context=context)
#         #build the id of this partner in the psql view. Could be replaced by a search with [('company_id', '=', company_id),('partner_id', '=', ids[0])]
        wizard_partner_ids = [ids[0] * 10000 + company_id]
        followup_ids = self.pool.get('crea8s.followup').search(cr, uid, [('company_id', '=', company_id)], context=context)
        if not followup_ids:
            raise osv.except_osv(_('Error!'),_("There is no followup plan defined for the current company."))
#         raise osv.except_osv(_('Error!'),"+followup_ids: " + str(followup_ids))
        data = {
            'date': fields.date.today(),
            'followup_id': followup_ids[0],
        }
        
        print 'do_print_overdue: '
        print '+ wizard_partner_ids: ' + str(wizard_partner_ids)
        print '+ data: ' + str(data)
        # ==========.==========.
        if not wizard_partner_ids:
            return {}
        data['partner_ids'] = wizard_partner_ids
        datas = {
             'ids': [], #??
             'model': 'crea8s.followup',
             'form': data,
        }
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'crea8s.followup.report',
            'datas': datas,
            }
        
    
    def do_mail_overdue_crea8s(self, cr, uid, ids, context=None):
        print 'do_mail_overdue'
        if context is None:
            context = {}
        ctx = context.copy() # okok, ?? 
        ctx['followup'] = True
        partner_ids = ids 
#         partner_ids are res.partner ids
        # If not defined by latest follow-up level, it will be the default template if it can find it

        mtp = self.pool.get('email.template')   
        unknown_mails = 0
        for partner in self.browse(cr, uid, partner_ids, context=ctx):
            if partner.email and partner.email.strip(): # ?? ....strip()
                level = partner.crea8s_latest_followup_level_id_without_lit
                if level and level.send_an_email and level.email_template_ref and level.email_template_ref.id:
                    mtp.send_mail(cr, uid, level.email_template_ref.id, partner.id, context=ctx)
                else:
                    mtp_from_xml = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crea8s_followup', 'email_template_crea8s_followup_default')
                    mtp.send_mail(cr, uid, mtp_from_xml[1], partner.id, context=ctx) 
#             
            else:
                unknown_mails = unknown_mails + 1
                action_text = _("Email not sent because of email address of partner not filled in - phongnd")
                if partner.crea8s_payment_next_action_date:
                    payment_action_date = min(fields.date.context_today(self, cr, uid, context=ctx), partner.crea8s_payment_next_action_date) 
                else:
                    payment_action_date = fields.date.context_today(self, cr, uid, context=ctx)
                if partner.crea8s_payment_next_action:
                    payment_next_action = partner.crea8s_payment_next_action + " \n " + action_text
                else:
                    payment_next_action = action_text
                self.write(cr, uid, [partner.id], {'crea8s_payment_next_action_date': payment_action_date,
                                                   'crea8s_payment_next_action': payment_next_action}, context=ctx)
        return unknown_mails
        
        
        
    

crea8s_followup_partner()






